package com.gitee.beiding.timer;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

//搜集并整合所有处理器
class Handlers {

    private static Map<String, TaskHandler> taskHandlerHashMap = new HashMap<>();

    Handlers(List<TaskHandler> taskHandlers) {
        taskHandlerHashMap.clear();
        for (TaskHandler taskHandler : taskHandlers) {
            TaskHandler handler = taskHandlerHashMap.put(taskHandler.name(), taskHandler);
            if (handler != null) {
                throw new RuntimeException("重名的Handler:" + handler.name());
            }
        }
    }

    private NoSuchTaskHandlerException noSuchTaskHandlerException = new NoSuchTaskHandlerException();

    //将会抛出没有这种处理器的异常
    void exe(Task task) {
        TaskHandler handler = taskHandlerHashMap.get(task.getName());
        if (handler == null) {
            throw noSuchTaskHandlerException;
        } else {
            try {
                handler.handle(task);
            } catch (Exception ignore) {
            }
        }
    }

}
